var  util=require('../base/Util');
var	 express = require('express');
var	 router = express.Router();
//数据库操作对象
var DbOpt = require("../models/Dbopt");
//材料
var Ingredient = require("../models/Ingredient");
//进货记录
var purchase = require("../models/Purchase");


var pageSize=20;



/*
 * 查询页面
 */
router.get("/init", function(req, res) {
	var page = util.di(req.query.page,1);
	var startdate=util.ds(req.query.startdate);
	var enddate=util.ds(req.query.enddate);
	var queryJson={};
	 var andArray=[];
	 var time1 = new Date().Format("yyyy-MM-dd");
	 if(startdate==""&&enddate==""){
		 startdate=time1;
		 enddate=time1;
	 }
	 
	if(startdate!=""){
		var dateCondition={};
		var tmp={};
		tmp["$gte"]=startdate+" 00:00:00";
		dateCondition["time"]=tmp;
		andArray.push(dateCondition);
	}
	if(enddate!=""){
		var dateCondition={};
		var tmp={};
		tmp["$lte"]=enddate+" 23:59:59";
		dateCondition["time"]=tmp;
		andArray.push(dateCondition);
	}
	if(startdate!=""||enddate!="")
		queryJson["$and"]=andArray;
	DbOpt.pagination(purchase,queryJson,page,pageSize,function(qinfo) {
		var sum=0;
		for(var i in qinfo.adocs){
			sum+=parseInt(qinfo.adocs[i].price);
		}
		res.render("purchase/purchase", {
			purchases : qinfo.docs,
			moment : require("moment"),
			total: qinfo.totalItems,
			page:qinfo.currentPage,
			startdate:startdate,
			enddate:enddate,
			totalPage:qinfo.totalPage,
			sum:sum
		});
	});
});

router.get("/addinit", function(req, res) {
	DbOpt.findAll(Ingredient,function(ingredients){
		res.render("purchase/purchase_add", {
			ingredients : ingredients
		});
	});

});


router.post("/add", function(req, res) {
	var remark=req.body.remark;
	var buyItems=req.body.buyItems;

	var addData={};
	addData["purchase_person"]="Edwin";
	addData["remark"]=req.body.remark;
	addData["buyitems"]=buyItems;
	addData["price"]=req.body.price;
	addData["time"]=new Date();

	DbOpt.addOne(purchase,addData,function(){
		res.json({success:1});
	});
});


router.post("/update", function(req, res) {
	var remark=req.body.remark;
	var buyItems=req.body.buyItems;

	var addData={};
	addData["purchase_person"]="Edwin";
	addData["remark"]=req.body.remark;
	addData["buyitems"]=buyItems;
	addData["price"]=req.body.price;
	addData["time"]=new Date();

	var id = req.body.id;
	DbOpt.updateOneByID(purchase,id,addData,function(){
		res.json({success:1});
	});
});


router.get("/editinit", function(req, res) {
	var id = req.query.id;
	var BSON = require('mongodb');
	var obj_id = BSON.ObjectID.createFromHexString(id);
	DbOpt.findAll(Ingredient,function(ingredients){
		DbOpt.findOne(purchase,id,function(purchases){
			res.render("purchase/purchase_edit", {
				ingredients : ingredients,
				purchases : purchases
			});
		});
	});
});

//删除材料
router.get("/del", function(req, res) {
	var id = req.query.id;
	DbOpt.del(purchase,id,function(){
		res.redirect('/purchase/init');
	});
});




module.exports = router;